package com.doge.walknovel.utils

import android.content.Intent
import android.net.Uri
import com.doge.wnpro.R
import com.doge.walknovel.api.*
import com.doge.walknovel.api.model.VersionInfo
import com.doge.walknovel.widgets.AlertDialog


object UpgradeHelper {
    private const val folder = "upgrade"
    private const val key = "remindedVersion"

    fun check() {
        api
            .versionInfo()
            .map(ApiResultMapTransformer())
            .subscribeOnIO()
            .observeOnMain()
            .subscribe(object : ObserverAdapter<VersionInfo>() {
                override fun onNext(t: VersionInfo) {
                    displayUpgradeDialog(t)
                }
            })
    }

    private fun displayUpgradeDialog(data: VersionInfo) {
        val context = Activities.top ?: return
        val remoteVersion = (data.versionNo ?: 0)
        if (remoteVersion > appVersionCode) {
            val remindedVersion = spReadInt(key, 0, folder)
            if (remoteVersion > remindedVersion) {
                AlertDialog.Builder(context)
                    .setTitle(data.title ?: getString(R.string.app_upgrade))
                    .setMessage(
                        data.remark ?: getString(R.string.there_is_a_new_version_in_the_app_market)
                    )
                    .setCancelable(false)
                    .apply {
                        if (data.forceUpdate) {
                            setAutoDismiss(false)
                            setPositiveButton(getString(R.string.to_market)) { _, _ ->
                                launchAppMarket(data.linkUrl)
                            }
                        } else {
                            setNegativeButton(getString(R.string.no_thanks)) { _, _ ->
                                spWrite(key, remoteVersion, folder)
                            }
                            setPositiveButton(getString(R.string.to_market)) { _, _ ->
                                launchAppMarket(data.linkUrl)
                            }
                        }
                    }
                    .create().show()
            }
        }
    }


    private fun launchAppMarket(link: String? = null) {
        launch(link) {
            launch("market://details?id=${appContext.packageName}") {
                launch("https://play.google.com/store/apps/details?id=${appContext.packageName}")
            }
        }
    }

    private fun launch(url: String?, failureCallback: () -> Unit = {}) {
        if (url.isNullOrEmpty()) {
            failureCallback()
        } else {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.data = Uri.parse(url)
            try {
                appContext.startActivity(intent)
            } catch (e: Throwable) {
                failureCallback()
            }
        }
    }
}

